<template>
  <a-modal
    v-model:visible="_d.visible"
    :title="_d.title"
    @ok="handleOk"
    @cancel="handleCancel"
    :okButtonProps="{ disabled: _d.loading }"
    :confirmLoading="_d.loading"
  >
    <a-form ref="formRef" :form="form" layout="vertical">
      <a-form-item
        v-for="field in _d.fields"
        :key="field.name"
        :label="field.label"
        :name="field.name"
        :rules="field.rules">
        <a-input v-model:value="_d.formData[field.name]" :placeholder="field.placeholder" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup>
import { ref, reactive, defineProps, defineEmits, onBeforeUnmount } from 'vue';
import { Modal, Form, Input } from 'ant-design-vue';

const props = defineProps({
  title: String,
  fields: Array,
});

const emit = defineEmits(['ok', 'cancel']);

const _d = reactive({
  visible: false,
  loading: false,

  formData: {},

  title: '',
  fields: [],
  onOk: null,
  onCancel: null,
})
const formRef = ref();
const form = Form.useForm(() => _d.formData);

const handleOk = async () => {
  try {
    _d.loading = true;
    const values = await formRef.value.validateFields();
    _d.onOk &&_d.onOk(values);
    _d.visible = false;
    _d.loading = false;
  } catch (error) {
    _d.loading = false;
    console.error('验证失败:', error);
  }
};

const handleCancel = () => {
  _d.visible = false;
  _d.onCancel && _d.onCancel();
};

// 提供方法显示弹窗
const show = (options) => {
  _d.title = options.title || '';
  _d.fields = options.fields || [];
  _d.onOk = options.onOk;
  _d.onCancel = options.onCancel;
  Object.keys(options.defaultValues || {}).forEach(key => {
    if (formData.value.hasOwnProperty(key)) {
      formData.value[key] = defaultValues[key];
    }
  });
  _d.visible = true;
};

// 暴露给父组件调用
defineExpose({ show });
</script>